/**
 * 2015-12-22
 * CourseDaoImpl.java
 * author:sherlochao
 */
package com.sherlochao.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.sherlochao.dao.CourseDao;
import com.sherlochao.model.Course;
import com.sherlochao.model.Student;
import com.sherlochao.model.StudyCourse;
import com.sherlochao.model.Teacher;

/**
 * @author yinchao
 *
 */
@Repository("courseDao")
public class CourseDaoImpl implements CourseDao{
	@Resource
	private SessionFactory sessionFactory;
	
	@Resource
	private CourseDao courseDao;
	
	public Session getSession() {
		return sessionFactory.openSession();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Course get(String id) {
		String hql = "from Course where id = ?";
		Query query = this.getSession().createQuery(hql);
		query.setString(0, id);
		return (Course) query.uniqueResult();
	}

	@Override
	public String save(Course entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(String id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Course load(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<StudyCourse> listStudyCourseByCourseId(String courseId) {
		// TODO Auto-generated method stub
		String hql = "from StudyCourse where course_id = ?";
		Query query = this.getSession().createQuery(hql);
		query.setString(0, courseId);
		List<StudyCourse> studyCourses = query.list();
		return studyCourses;
	}

	@Override
	public List<Student> listStudentByCourseId(String courseId) {
		// TODO Auto-generated method stub
		List<StudyCourse> studyCourses = courseDao.listStudyCourseByCourseId(courseId);
		List<Student> students = new ArrayList<Student>();
		for(int i = 0; i < studyCourses.size(); i++){
			String hql = "from Student where id = ?";
			Query query = this.getSession().createQuery(hql);
			query.setString(0, studyCourses.get(i).getStudentId());
			students.add((Student)query.uniqueResult());
		}
		return students;
	}

	@Override
	public List<Teacher> listTeacherByCourseId(String courseId) {
		// TODO Auto-generated method stub
		List<Student> students = courseDao.listStudentByCourseId(courseId);
		List<Teacher> teachers = new ArrayList<Teacher>();
		for(int i = 0; i < students.size(); i++){
			String hql = "from Teacher where id = ?";
			Query query = this.getSession().createQuery(hql);
			query.setString(0, students.get(i).getTeacherId());
			teachers.add((Teacher)query.uniqueResult());
		}
		return teachers;
	}
	
	

}
